// filename: IpEndpoint.cpp
// author: enic
// date: 2015-06-26

#pragma once

#include "IpEndpoint.h"
#include "string_utf_convert.h"

#ifdef WIN32
	#include <WinSock2.h>
	#include <Ws2tcpip.h>
	#pragma comment(lib,"Ws2_32.lib")

	#ifdef SetPort
		#undef SetPort
	#endif
#endif // WIN32

const std::string IpEndpoint::GetIpAsString() const
{
	struct in_addr addr;
	memcpy(&addr, &m_u32IP, sizeof(m_u32IP));
	return inet_ntoa(addr);
}

uint32_t IpEndpoint::IpFromString(const std::string& strIp)
{
	uint32_t u32Ip = 0;
	::inet_ntop(AF_INET, (void *)&u32Ip, const_cast<char*>(strIp.data()), strIp.size());

	return u32Ip;
}

uint32_t IpEndpoint::IpFromString(const std::wstring& strIp)
{
	uint32_t u32Ip;
	const std::string strIpA = XU16T8(strIp);
	::inet_ntop(AF_INET, (void *)&u32Ip, const_cast<char*>(strIpA.data()), strIpA.size());

	return u32Ip;
}

IpEndpoint IpEndpoint::IpEndpointFromString(const std::string& strIpEndPoint)
{
	IpEndpoint ipEndpoint;

	return ipEndpoint;
}

IpEndpoint IpEndpoint::IpEndpointFromString(const std::wstring& strIpEndPoint)
{
	IpEndpoint ipEndpoint;

	return ipEndpoint;
}

IpEndpoint IpEndpoint::IpEndpointFromLoopBackPort(uint16_t u16Port)
{
	IpEndpoint ipEndpoint;

	ipEndpoint.SetIp(IpFromString("127.0.0.1"));
	ipEndpoint.SetPort(u16Port);

	return ipEndpoint;
}


#ifdef WIN32
	#ifdef UNICODE
		#define SetPort  SetPortW
	#else
		#define SetPort  SetPortA
	#endif // !UNICODE
#endif // WIN32